package 剑指Offer._6170;

import general_class.TreeNode;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/12/23 13:30
 * 二叉树的最近公共祖先
 * 算法：递归
 * 遍历左子树和右子树
 */
public class _68II {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return root;
        if (root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null) return right;
        else if (right == null) return left;
        else return root;
    }

}
